
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const todosCollection = db.collection('todos')

// 订阅消息模板ID
const REMINDER_TEMPLATE_ID = '695PQ8se07fitLzQBZmv6oI0MFhpG501-HNahY1vcUU' // 待办提醒模板ID

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 获取需要提醒的待办事项
    const now = new Date()
    const fiveMinutesLater = new Date(now.getTime() + 5 * 60 * 1000)

    const todos = await todosCollection.where({
      reminderTime: _.gte(now).and(_.lt(fiveMinutesLater)),
      status: false, // 只提醒未完成的
      notified: _.neq(true) // 未发送过提醒
    }).get()

    if (todos.data.length === 0) {
      return {
        code: 0,
        msg: '没有需要提醒的待办事项'
      }
    }

    // 发送提醒
    const sendPromises = todos.data.map(async todo => {
      try {
        // 发送订阅消息
        await cloud.openapi.subscribeMessage.send({
          touser: todo.userId,
          templateId: REMINDER_TEMPLATE_ID,
          data: {
            // 根据实际申请的模板格式填写
            thing1: { value: todo.title }, // 待办事项标题
            time2: { value: formatDateTime(todo.reminderTime) }, // 提醒时间
            thing3: { value: todo.content || '无详细内容' }, // 待办事项内容
            thing4: { value: todo.tags.join(',') || '无标签' } // 标签
          },
          // 点击消息跳转的页面
          page: `pages/edit/index?id=${todo._id}`
        })

        // 更新提醒状态
        await todosCollection.doc(todo._id).update({
          data: {
            notified: true,
            notifyTime: db.serverDate()
          }
        })

        return {
          todoId: todo._id,
          success: true
        }
      } catch (err) {
        console.error(`[发送提醒失败] todoId: ${todo._id}`, err)
        return {
          todoId: todo._id,
          success: false,
          error: err
        }
      }
    })

    const results = await Promise.all(sendPromises)
    const successCount = results.filter(r => r.success).length
    const failCount = results.filter(r => !r.success).length

    return {
      code: 0,
      msg: `提醒发送完成：成功${successCount}条，失败${failCount}条`,
      data: results
    }
  } catch (err) {
    console.error('[执行提醒任务]失败：', err)
    return {
      code: -1,
      msg: '执行提醒任务失败',
      error: err
    }
  }
}

// 格式化日期时间
function formatDateTime(date) {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  const hour = d.getHours().toString().padStart(2, '0')
  const minute = d.getMinutes().toString().padStart(2, '0')
  
  return `${year}年${month}月${day}日 ${hour}:${minute}`
}